/**
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package fr.generali.accueilclient.utils.spel.mapping.support;

import java.util.Collections;
import java.util.Set;

import org.springframework.core.GenericTypeResolver;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import fr.generali.accueilclient.utils.spel.mapping.Mapper;

/**
 * Adapts a Mapper to a Converter, allowing the conversion between two object
 * types to be completed by a Mapper. Delegates to a
 * {@link MappingTargetFactory} to construct the conversion target object that
 * will be mapped. The default MapperTargetFactory instantiates a target by
 * calling its default constructor.
 * 
 * @author Keith Donald
 */
public class MappingConverter implements GenericConverter {

    /**
     * 
     */
    private final Set<ConvertiblePair> convertibleTypes;

    /**
	 * 
	 */
    private final Mapper mapper;

    /**
	 * 
	 */
    private final MappingTargetFactory mappingTargetFactory;

    /**
     * Creates a new Converter that delegates to the mapper to complete the type
     * conversion process. Uses the specified MappingTargetFactory to create the
     * target object to map and return.
     * 
     * @param mapper the mapper
     */
    public MappingConverter(Mapper< ? , ? > mapper, MappingTargetFactory mappingTargetFactory) {
        this.mapper = mapper;
        if (mappingTargetFactory != null) {
            this.mappingTargetFactory = mappingTargetFactory;
        } else {
            this.mappingTargetFactory = DefaultMappingTargetFactory.getInstance();
        }
        this.convertibleTypes = Collections.singleton(getRequiredTypeInfo(mapper, Mapper.class));
    }

    /**
     * {@inheritDoc}
     */
    public Set<ConvertiblePair> getConvertibleTypes() {
        return this.convertibleTypes;
    }

    /**
     * {@inheritDoc}
     */
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        if (MappingContextHolder.contains(source)) {
            return source;
        }
        if (sourceType.isAssignableTo(targetType) && isCopyByReference(sourceType, targetType)) {
            return source;
        }
        return createTargetAndMap(source, sourceType, targetType);
    }

    /**
     * @param converter converter
     * @param genericIfc generic
     * @return GenericConverter.ConvertiblePair
     */
    private GenericConverter.ConvertiblePair getRequiredTypeInfo(Object converter, Class< ? > genericIfc) {
        Class< ? >[] args = GenericTypeResolver.resolveTypeArguments(converter.getClass(), genericIfc);
        if (args == null) {
            throw new IllegalArgumentException("Unable to the determine sourceType <S> and targetType <T> which "
                            + "your Mapper<S, T> converts between; declare these generic types.");
        }
        return new GenericConverter.ConvertiblePair(args[0], args[1]);
    }

    /**
     * @param sourceType source type
     * @param targetType target type
     * @return true if copy by reference
     */
    private boolean isCopyByReference(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return true;
    }

    /**
     * @param source source
     * @param sourceType source type
     * @param targetType target type
     * @return object
     */
    private Object createTargetAndMap(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (this.mappingTargetFactory.supports(targetType)) {
            Object target = this.mappingTargetFactory.createTarget(source, sourceType, targetType);
            return this.mapper.map(source, target);
        } else {
            IllegalStateException cause =
                            new IllegalStateException("[" + this.mappingTargetFactory.getClass().getName()
                                            + "] does not support targetType [" + targetType.getName() + "]");
            throw new ConversionFailedException(sourceType, targetType, source, cause);
        }
    }

}
